package edu.tyut.game.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

@Slf4j
@Component
public class SocketConfig {

    private Socket socket;
    private PrintWriter pw;

    @Value("${socket.port}")
    private int port;


    public void getSocket(){
        Thread thread = new Thread(() -> {
            try (ServerSocket serverSocket = new ServerSocket(port)) {
                log.debug("port: " + port);
                socket = serverSocket.accept();
                log.debug("连接成功..., port: " + port);
                initPw();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });
        thread.start();
        // Timer timer = new Timer();
        // timer.schedule(new TimerTask() {
        //     @Override
        //     public void run() {
        //         log.debug("socket: " + socket);
        //         if (socket != null){
        //             log.debug("socket.isClosed: " + socket.isClosed());
        //             log.debug("socket.isConnected: " + socket.isConnected());
        //         }
        //     }
        // }, 0, 3000);
    }

    public void initPw(){
        if (socket != null && socket.isConnected()){
            try {
                pw = new PrintWriter(socket.getOutputStream());
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public void writeInfo(String info){
        pw.println(info);
        pw.flush();
    }

    @Override
    protected void finalize() throws Throwable {
        if (socket.isConnected()) {
            socket.close();
            log.debug("socket 关闭...");
        }
    }
}
